package com.turing.post.account.impl;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.account.util.AccountSystemTradDetail;
import com.turing.post.account.util.AccountSystemTradDetailDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

@Stateless(mappedName = "account.impl.AccountSystemTradDetailDaoImpl")
@Remote
@Local
public class AccountSystemTradDetailDaoImpl implements
		AccountSystemTradDetailDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	/**
	 * 插入帐户子系统交易流水记录
	 */
	public void insert(AccountSystemTradDetail astd)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, astd);
	}

	/**
	 * 更新
	 * 
	 * @param astd
	 * @throws PCPSApplicationException
	 */
	public void update(AccountSystemTradDetail astd)
			throws PCPSApplicationException {
		GeneralDao.update(_em, astd);
	}

	/**
	 * 根据帐户子系统流水号从帐户子系统交易流水表检索
	 * 
	 * @param accSeqNo
	 * @return
	 */
	public AccountSystemTradDetail getAccountSystemTradDetailByAccSeqNo(
			String accSeqNo) {
		return _em.find(AccountSystemTradDetail.class, accSeqNo);
	}

	/**
	 * 根据帐户子系统流水号从帐户子系统交易历史流水表检索
	 * 
	 * @param accSeqNo
	 * @return
	 */
	public AccountSystemTradDetail getAccountSystemHisTradDetailByAccSeqNo(
			String accSeqNo) {
		Query query = _em
				.createNativeQuery(
						"select t.* from AccountSystemTradDetail t where t.accSeqNo = ?1 for update",
						AccountSystemTradDetail.class);
		query.setParameter(1, accSeqNo);
		return ((AccountSystemTradDetail) query.getSingleResult());
	}

	/**
	 * 更新历史交易流水的三个撤销字段
	 * 
	 * @param astd
	 */
	public int cancelAccountSystemHisTradDetail(AccountSystemTradDetail astd) {
		Query query = _em
				.createNativeQuery("update AccountSystemHisTradDetail "
						+ "set CancelAccSeqNo = ?2, CancelTranDate = ?3, CancelTranSeqNo = ?4"
						+ "where accSeqNo = ?1");
		query.setParameter(1, astd.getAccSeqNo());
		query.setParameter(2, astd.getCancelAccSeqNo());
		query.setParameter(3, astd.getCancelTranDate());
		query.setParameter(4, astd.getCancelTranSeqNo());
		return query.executeUpdate();
	}

	/**
	 * 重置某交易流水的三个Cancel字段为NULL
	 * 
	 * @param accSeqNo
	 * @throws PCPSApplicationException
	 */
	public void resetCancelInf(String accSeqNo) throws PCPSApplicationException {
		Query query = _em
				.createNativeQuery("update AccountSystemTradDetail "
						+ "set CancelAccSeqNo = NULL, CancelTranDate = NULL, CancelTranSeqNo = NULL where accSeqNo = ?1");
		query.setParameter(1, accSeqNo);
		query.executeUpdate();
	}
}